package parent

import (
	"anban/controllers"
	"anban/service"
	"anban/utils"
	"encoding/json"
	"fmt"
	"html/template"
	"net/url"
)

type IndexController struct {
	controllers.BaseController
}

func (c *IndexController) Index() {
	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["id"] = userId
	user := service.GetUserInfo(p)

	var studentIds []int64
	p = map[string]interface{}{}
	p["status"] = 1
	p["familySn"] = user.FamilySn
	studentNum, studentList := service.GetStudentList(p)
	for _, student := range studentList {
		studentIds = append(studentIds, student.Id)
	}
	c.Data["studentNum"] = studentNum

	p = map[string]interface{}{}
	p["status"] = 1
	p["familySn"] = user.FamilySn
	c.Data["familyNum"], _ = service.GetUserList(p)

	p = map[string]interface{}{}
	p["relation"] = true
	p["convert"] = true
	p["limit"] = 10
	p["studentIds"] = studentIds
	_, c.Data["newNoticeList"] = service.GetNewNoticeList(p)

	c.Data["title"] = "首页"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "parent/index.html"
}

func (c *IndexController) Register() {
	p := map[string]interface{}{}
	_, relationList := service.GetStudentRelationList(p)
	relationValues := service.GetStudentRelationListValues(relationList)
	res, _ := json.Marshal(relationValues)
	c.Data["relationJson"] = string(res)

	c.Data["title"] = "家长注册"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "parent/register.html"
}

func (c *IndexController) DoRegister() {
	var res *utils.ResJsonStruct
	input := c.Input()

	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["id"] = userId
	user := service.GetUserInfo(p)

	if user.Identity == 0 {
		if len(input["user_phone"][0]) <= 0 {
			res = utils.ResJson(0, "请输入您的手机号", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
		if !utils.IsMobile(input["user_phone"][0]) {
			res = utils.ResJson(0, "请输入正确的手机号", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
		verifyRes, verifyMsg := service.DoCheckVerifyCode(input["user_phone"][0], input["verify_code"][0])
		if !verifyRes {
			res = utils.ResJson(0, verifyMsg, "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
		if len(input["user_real_name"][0]) <= 0 {
			res = utils.ResJson(0, "请输入您的姓名", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
	}
	if len(input["student_real_name"][0]) <= 0 {
		res = utils.ResJson(0, "请输入孩子的姓名", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["student_id_card"][0]) <= 0 {
		res = utils.ResJson(0, "请输入孩子的身份证号", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["student_relation_id"][0]) <= 0 {
		res = utils.ResJson(0, "请选择您与孩子的关系", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	p = map[string]interface{}{}
	p["realName"] = input["student_real_name"][0]
	p["idCard"] = input["student_id_card"][0]
	student := service.GetStudentInfo(p)
	if student.Id <= 0 {
		res = utils.ResJson(0, "请检查孩子的姓名和身份证号是否正确", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	if user.StudentRelation.Id > 0 {
		res = utils.ResJson(0, "注册失败，您已经注册过了", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	var addInput url.Values
	var editInput url.Values

	familySn := student.FamilySn
	if len(familySn) <= 0 {
		familySn = user.FamilySn
		if len(familySn) <= 0 {
			familySn = service.GetUserFamilySn()
		}
		editInput = url.Values{
			"id": {fmt.Sprintf("%d", student.Id)},
			"family_sn": {familySn},
		}
		_, err := service.EditStudent(editInput)
		if err != nil {
			res = utils.ResJson(0, "注册失败，请稍候重试", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
		editInput = url.Values{
			"id": {fmt.Sprintf("%d", user.Id)},
			"is_main": {"1"},
			"student_relation_id": {input["student_relation_id"][0]},
		}
	} else {
		if len(user.FamilySn) > 0 && user.FamilySn != familySn {
			res = utils.ResJson(0, fmt.Sprintf("%s不是您的孩子", student.RealName), "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
		if len(user.FamilySn) > 0 && user.FamilySn == familySn {
			res = utils.ResJson(0, "您已经注册过了，请不要重复操作", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
		editInput = url.Values{
			"id": {fmt.Sprintf("%d", user.Id)},
			"is_main": {"0"},
			"student_relation_id": {input["student_relation_id"][0]},
		}
	}
	editInput["family_sn"] = []string{familySn}

	if user.Identity == 2 {
		editInput["identity"] = []string{"3"}
	} else {
		editInput["identity"] = []string{"1"}
	}
	if _, ok := input["user_real_name"]; ok {
		editInput["real_name"] = []string{input["user_real_name"][0]}
	}
	if _, ok := input["user_phone"]; ok {
		editInput["phone"] = []string{input["user_phone"][0]}
	}
	_, err := service.EditUser(editInput)
	if err != nil {
		res = utils.ResJson(0, "注册失败，请稍候重试", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	addInput = url.Values{
		"user_id": {fmt.Sprintf("%d", user.Id)},
		"student_id": {fmt.Sprintf("%d", student.Id)},
	}
	_, err = service.AddUserStudent(addInput)
	if err != nil {
		res = utils.ResJson(0, "注册失败，请稍候重试", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res = utils.ResJson(1, "注册成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *IndexController) InviteRegister() {
	p := map[string]interface{}{}
	_, relationList := service.GetStudentRelationList(p)
	relationValues := service.GetStudentRelationListValues(relationList)
	res, _ := json.Marshal(relationValues)
	c.Data["relationJson"] = string(res)

	c.Data["title"] = "家长注册"
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "parent/invite-register.html"
}

func (c *IndexController) DoInviteRegister() {
	var res *utils.ResJsonStruct
	input := c.Input()

	if len(input["phone"][0]) <= 0 {
		res = utils.ResJson(0, "请输入您的手机号", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	verifyRes, verifyMsg := service.DoCheckVerifyCode(input["phone"][0], input["verify_code"][0])
	if !verifyRes {
		res = utils.ResJson(0, verifyMsg, "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["real_name"][0]) <= 0 {
		res = utils.ResJson(0, "请输入您的姓名", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if len(input["student_relation_id"][0]) <= 0 {
		res = utils.ResJson(0, "请选择您与孩子的关系", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["id"] = userId
	user := service.GetUserInfo(p)

	if user.StudentRelation.Id > 0 {
		res = utils.ResJson(0, "注册失败，您已经注册过了", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	var addInput url.Values
	var editInput url.Values

	p = map[string]interface{}{}
	p["familySn"] = user.FamilySn
	_, studentList := service.GetStudentList(p)

	for _, student := range studentList {
		addInput = url.Values{
			"user_id": {fmt.Sprintf("%d", user.Id)},
			"student_id": {fmt.Sprintf("%d", student.Id)},
		}
		_, err := service.AddUserStudent(addInput)
		if err != nil {
			res = utils.ResJson(0, "注册失败，请稍候重试", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
	}

	editInput = url.Values{
		"id": {fmt.Sprintf("%d", user.Id)},
		"phone": {input["phone"][0]},
		"real_name": {input["real_name"][0]},
		"student_relation_id": {input["student_relation_id"][0]},
	}
	if user.Identity == 2 {
		editInput["identity"] = []string{"3"}
	} else {
		editInput["identity"] = []string{"1"}
	}
	service.EditUser(editInput)

	res = utils.ResJson(1, "注册成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}